package com.huishu.commons.utlis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.*;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName：HttpClientUtil
 * @Author: ljj
 * @Date: 2022/6/22 15:41
 */
@Slf4j
@SuppressWarnings("All")
public class HttpClientUtil {

    private String url;
    private Map<String, Object> param;
    private int statusCode;
    private String content;
    private String xmlParam;
    private boolean isHttps;
    private String body;
    private String authorization;

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public boolean isHttps() {
        return isHttps;
    }

    public void setHttps(boolean isHttps) {
        this.isHttps = isHttps;
    }

    public String getXmlParam() {
        return xmlParam;
    }

    public void setXmlParam(String xmlParam) {
        this.xmlParam = xmlParam;
    }

    public HttpClientUtil(String url, Map<String, Object> param) {
        this.url = url;
        this.param = param;
    }

    public HttpClientUtil(String url) {
        this.url = url;
    }

    public void setParameter(Map<String, Object> map) {
        param = map;
    }

    public void addParameter(String key, String value) {
        if (param == null) {
            param = new HashMap<String, Object>();
        }
        param.put(key, value);
    }

    public void post() {
        try {
            HttpPost http = new HttpPost(url);
            setEntity(http);
            execute(http);
            if (StringUtils.isNotEmpty(authorization)) {
                http.setHeader("Authorization", authorization);
            }
        } catch (IOException e) {
            log.error("post请求异常");
        }
    }

    public void post(String appKey, String random, String sign, String timestamp, String data) throws ClientProtocolException, IOException {
        HttpPost http = new HttpPost(url);
        http.setHeader("appKey", appKey);
        http.setHeader("random", random);
        http.setHeader("sign", sign);
        http.setHeader("timestamp", timestamp);
        http.setHeader("data", data);
        setEntity(http);
        execute(http);
        if (StringUtils.isNotEmpty(authorization)) {
            http.setHeader("Authorization", authorization);
        }
    }

    public void put() throws ClientProtocolException, IOException {
        HttpPut http = new HttpPut(url);
        setEntity(http);
        execute(http);
    }

    public void get() throws ClientProtocolException, IOException {
        if (param != null) {
            StringBuilder url = new StringBuilder(this.url);
            boolean isFirst = true;
            for (String key : param.keySet()) {
                if (isFirst) {
                    url.append("?");
                    isFirst = false;
                } else {
                    url.append("&");
                }
                url.append(key).append("=").append(param.get(key));
            }
            this.url = url.toString();
        }
        log.info("url:{}", url);
        HttpGet http = new HttpGet(url);
        if (StringUtils.isNotEmpty(authorization)) {
            http.setHeader("Authorization", authorization);
        }
        execute(http);
    }

    /**
     * set http post,put param
     */
    private void setEntity(HttpEntityEnclosingRequestBase http) {
        if (null != body) {
            // 设置参数
            StringEntity entity = new StringEntity(body, ContentType.APPLICATION_JSON);
            http.setEntity(entity);
        }
        if (param != null) {
            //List<NameValuePair> nvps = new LinkedList<NameValuePair>();
            //for (String key : param.keySet()) {
            //    // 参数
            //    nvps.add(new BasicNameValuePair(key, param.get(key).toString()));
            //}
            // 设置参数
            StringEntity entity = new StringEntity(JSON.toJSONString(param), ContentType.APPLICATION_JSON);
            http.setEntity(entity);
        }
        if (xmlParam != null) {
            http.setEntity(new StringEntity(xmlParam, Consts.UTF_8));
        }
    }

    private void execute(HttpUriRequest http) throws ClientProtocolException,
            IOException {
        CloseableHttpClient httpClient = null;
        try {
            if (isHttps) {
                SSLContext sslContext = new SSLContextBuilder()
                        .loadTrustMaterial(null, new TrustStrategy() {
                            // 信任所有
                            @Override
                            public boolean isTrusted(X509Certificate[] chain,
                                                     String authType)
                                    throws CertificateException {
                                return true;
                            }
                        }).build();
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                        sslContext);
                httpClient = HttpClients.custom().setSSLSocketFactory(sslsf)
                        .build();
            } else {
                httpClient = HttpClients.createDefault();
            }
            CloseableHttpResponse response = httpClient.execute(http);
            try {
                if (response != null) {
                    if (response.getStatusLine() != null) {
                        statusCode = response.getStatusLine().getStatusCode();
                    }
                    HttpEntity entity = response.getEntity();


                    String res = EntityUtils.toString(response.getEntity(), "GBK");
                    JSONObject json = JSONObject.parseObject(res);
                    // 响应内容
                    content = JSONObject.toJSONString(json);
                }
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpClient.close();
        }
    }

    public int getStatusCode() {
        return statusCode;
    }

    public String getContent() {
        return content;
    }

    public String getAuthorization() {
        return authorization;
    }

    public void setAuthorization(String authorization) {
        this.authorization = authorization;
    }
}
